'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');

class HomeController extends Controller {
    //登录
    async login() {
        const { ctx,service } = this;
        let {username,password } = ctx.request.body;
        //手机号的正则
        if(username && /\w{4,6}/.test(password)){  //容错处理
            let user = await service.home.login(username,password);
            if(user.length){
                let {id,username,role_id,role_name} = user[0];
                let token = jwt.sign({uid:id},'yuekao',{expiresIn:60*60});
                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    token,
                    username,
                    role_name,
                    role_id
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //获取菜单
    async menuList(){
        let {ctx,service} = this;
        let {role_id} = ctx.query;
        if(role_id){
            console.log("======")
            let menuList = await service.home.menuList(role_id);
            ctx.body = {
                code:1,
                data:menuList
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
}

module.exports = HomeController;
